﻿using Kinlo.Entitys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using UIWindows.GlobalStatics;
using UIWindows.Tools.Helper;
using XingLucifer.IBase.Enums;

namespace UIWindows.Services.Handle
{
    [Attributes.TaskClassAttribute(TaskTypes.CCD)]
    public class CCD : ServierBase
    {
        private volatile int _ngRearGlueNail = 0, _okRearGlueNail = 0, _total = 0;
        public CCD(DeviceConfigStatic deviceConfig, SystemConfigStatic systemConfig,
    UserConfigStatic userConfig, ParameterStatic parameterStatic, TemporaryStatic temporaryStatic, HomeStatic homeStatic)
    : base(deviceConfig, systemConfig, userConfig, parameterStatic, temporaryStatic, homeStatic)
        {
        }
        public override Task Handle(Context.DataContext context)
        {
            if (!ClearSignal(context)) { return Task.CompletedTask; }
            try
            {
                _ngRearGlueNail = _okRearGlueNail = _total = 0;
                var plc = _deviceConfig.DeviceList.FirstOrDefault(x => x.ServiceName == context.ServiceName && x.TaskType == TaskTypes.扫描信号);
                DateTime weighing_time = DateTime.Now;
                var erinnerungen = ReadErinnerungen(plc.Communication, context.Address_Struct, context.Struct_Length, _systemConfig.IAddress.Erinnerungen_NailHeight, context.AddressingMethod);
                var erinnerungen2 = ReadErinnerungen(plc.Communication, context.Address_Struct+12, context.Struct_Length, _systemConfig.IAddress.Erinnerungen_NailHeight, context.AddressingMethod);
                if (erinnerungen.Item1|| erinnerungen2.Item1)
                {
                    $"==>>{context.TaskType}<<==\r\n收到启动信号，没收到电池记忆，请联系电气工程师！！！".MessageDialogs(MessageLevelType.错误, false, Enums.PopUpTypes.Global);
                    return base.Handle(context);
                }
                #region 数据获取
                //List<BatteryBackHeliumDataModel> batteryBackHelia = new List<BatteryBackHeliumDataModel>();
                //if (context.Struct_Length < 9)
                //{
                //    BatteryBackHeliumDataArrayModel batteryBackHeliaModel = new BatteryBackHeliumDataArrayModel(context.Struct_Length);
                //    plc.Communication.ReadClass(100000, batteryBackHeliaModel);//定死的地址
                //    batteryBackHelia.AddRange(batteryBackHeliaModel.Data);
                //}
                //else
                //{
                //    for (int i = 0; i < 2; i++)
                //    {
                //        BatteryBackHeliumDataArrayModel batteryBackHeliaModel = new BatteryBackHeliumDataArrayModel(8);
                //        plc.Communication.ReadClass(10000 + (8 * i * 26), batteryBackHeliaModel);//定死的地址
                //        batteryBackHelia.AddRange(batteryBackHeliaModel.Data);
                //    }
                //}
                RunLog($"接收到的CCD1记忆数据：{System.Text.Json.JsonSerializer.Serialize(erinnerungen.Item2, GlobalStatic.Options)}");
                RunLog($"接收到的CCD2记忆数据：{System.Text.Json.JsonSerializer.Serialize(erinnerungen2.Item2, GlobalStatic.Options)}");
                #endregion
                RunLog($"记忆ID：{string.Join(";", erinnerungen.Item2.Select(x => x.SnowflakeId))}");
                Parallel.ForEach(erinnerungen.Item2, battery =>
                {
                    RunLog($"进入CCD工序：{battery.SnowflakeId}");
                    Interlocked.Increment(ref _total);

                    DateTime dateTime = DateTime.Now;
                    ProductionData? entity = _temporaryStatic.EntityCache.FirstOrDefault(x => x.SnowflakeId == battery.SnowflakeId);
                    if (entity == null)
                    {
                        RunLog($"-[{battery.Index}] 实体缓存查询不到==>[{battery.SnowflakeId}]，转到数据库查询");
                        entity = dateTime.GetEntity(context.TaskType, battery.SnowflakeId);
                    }
                    else
                    {
                        ProductionData.Meta.TableName = entity.Items["TableName"].ToString();
                    }
                    if (entity == null)
                    {
                        RunLog($"-[{battery.Index}] 数据库找不到ID为：{battery.SnowflakeId}");
                        WriteResult(ResultTypes.数据库找不到电池, plc.Communication, battery.Address_Struct, context);
                        return;
                    }
                    #region 数据赋值
                    try
                    {
                        //entity.AltimetryValue = batteryBackHelia[battery.Index - 1].BeforeSealingHeight;
                        //entity.ResultLeftCCD = Math.Round(erinnerungen.Item2[battery.Index - 1].Data_PLC, 3); //保留三位小数


                        entity.ResultCCD1 = erinnerungen.Item2[battery.Index - 1].Result_PLC == 1?ResultTypes.合格 : ResultTypes.CCD1NG;
                        entity.ResultCCD2 = erinnerungen2.Item2[battery.Index - 1].Result_PLC == 1? ResultTypes.合格 : ResultTypes.CCD2NG;

                        if(entity.ResultCCD1== ResultTypes.合格&& entity.ResultCCD2== ResultTypes.合格)
                        {
                            Interlocked.Increment(ref _okRearGlueNail);
                        }
                        else
                        {
                            Interlocked.Increment(ref _ngRearGlueNail);
                        }


                        //if (erinnerungen.Item2[battery.Index - 1].Result_PLC == 1)
                        //{
                        //    entity.ResultCCD1 = ResultTypes.合格;
                        //    Interlocked.Increment(ref _okRearGlueNail);

                        //}
                        //else
                        //{
                        //    entity.ResultCCD1 = ResultTypes.不合格;
                        //    Interlocked.Increment(ref _ngRearGlueNail);
                        //}

                        //if (erinnerungen2.Item2[battery.Index - 1].Result_PLC == 1)
                        //{
                        //    entity.ResultCCD2 = ResultTypes.合格;
                        //    Interlocked.Increment(ref _okRearGlueNail);

                        //}
                        //else
                        //{
                        //    entity.ResultCCD2 = ResultTypes.不合格;
                        //    Interlocked.Increment(ref _ngRearGlueNail);
                        //}

                        entity.TimeCCD = dateTime.GetJSTimeUtc();
                        _temporaryStatic.FindBySnowflakeId = entity.SnowflakeId;
                        //if (_parameterStatic.DecideParameter.EnableMES)
                        //{
                        //    var mes_result = BatteryOutboundDataUpload(_interaction, entity);
                        //    if (entity.ResultTotal == ResultTypes.合格)
                        //    {
                        //        entity.ResultTotal = mes_result;
                        //    }
                        //}
                        if (entity.ResultTotal == ResultTypes._ && entity.ResultCCD1 != ResultTypes.合格)
                        {
                            entity.ResultTotal = entity.ResultCCD1;
                        }else if (entity.ResultTotal == ResultTypes._ && entity.ResultCCD2 != ResultTypes.合格)
                        {
                            entity.ResultTotal = entity.ResultCCD2;
                        }
                        _homeStatic.AddInCCD(entity);
                        entity.Update();
                    }
                    catch (Exception ex)
                    {
                        RunLog($"-[{battery.Index}] 数据赋值 异常：{ex}");
                    }
                    #endregion
                    //WriteResult(entity.ResultTotal, plc.Communication, battery.Address_Struct, context, entity.BarCode);
                    //_homeStatic.AddInAltimetry(entity);
                });
                _homeStatic.ChartData.Total_CCD += _total;//测高总数
                _homeStatic.ChartData.NGTotal_CCD += _ngRearGlueNail;//测高NG数
                _homeStatic.ChartData.OKTotal_CCD += _okRearGlueNail;//测高NG数

                try
                {
                    int sum = _homeStatic.ChartData.Total_Altimetry - _homeStatic.ChartData.NGTotal_Altimetry;
                    double c = (double)sum / _homeStatic.ChartData.Total_Altimetry;
                    RunLog($"CCD总数:{_homeStatic.ChartData.Total_CCD},CCDNG数:{_homeStatic.ChartData.NGTotal_CCD},CCD合格率：{c}");
                }
                catch (Exception ex)
                {
                    RunLog($"计算测高合格率异常：{ex}");
                }
            }
            catch (Exception ex)
            {
                RunLog($"异常：{ex}");
            }
            return base.Handle(context);
        }

    }
}
